class PhotoSize < ActiveRecord::Base
  has_many                  :items
  belongs_to                :price_list
  validates_presence_of     :size
  validates_presence_of     :cost
  validates_numericality_of :cost
  
  after_destroy             :ensure_atleast_one_photo_size_persists
  after_destroy             :find_and_change_effected_items
  
protected
  def find_and_change_effected_items
    self.items.each {|item| item.update_attributes!(:photo_size => PhotoSize.find(:all, :order => 'cost asc').first)}
  end
  def ensure_atleast_one_photo_size_persists
    PhotoSize.create!(:size => "N/A", :cost => "0.0", :price_list => PriceList.find(:all).first) if PhotoSize.find(:all).empty?
  end
end
